package com.chen.androidstudy.utils;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;

/**
 * @Author ch
 * @Date 2024/1/23 16:26
 * @Des: 手机app本身的安全检测
 */
public class SecurityUtils {

    private static final String TAG = "SecurityUtils";

    /**
     * 检测是否安全
     *
     * @param context
     * @return true 是安全的，false 不安全
     */
    public static boolean checkIfSecurity(Context context) {
        boolean ifSecurity = true;
        ifSecurity = !isRunInVirtual(context) && !checkGetRootAuth() && !isWifiProxy(context);
        return ifSecurity;
    }

    /**
     * 检查是否有多开
     *
     * @return
     */
    private static boolean isRunInVirtual(Context context) {
        String filter = context.getPackageName();
        String result = execStr();
        if (result == null || result.isEmpty()) {
            return false;
        }
        String[] lines = result.split("\n");
        if (lines == null || lines.length == 0) {
            return false;
        }

        int exitDirCount = 0;

        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains(filter)) {
                int pkgStartIndex = lines[i].lastIndexOf(" ");
                String processName = lines[i].substring(pkgStartIndex <= 0
                        ? 0 : pkgStartIndex + 1, lines[i].length());
                File dataFile = new File(String.format("/data/data/%s",
                        processName, Locale.CHINA));
                if (dataFile.exists()) {
                    exitDirCount++;
                }
            }
        }
        boolean back = exitDirCount > 1;
        if (back) {
            Logger.d(TAG, " fail, isRunInVirtual exitDirCount: " + exitDirCount);
        }
        return back;
    }

    /**
     * 获取ps数据
     *
     * @return
     */
    private static String execStr() {
        String outStr = "";
        try {
            Process process = Runtime.getRuntime().exec("ps");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer buffer = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                // 处理命令的输出
                buffer.append(line);
            }
            outStr = buffer.toString();
            process.waitFor(); // 等待命令执行完成
            reader.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            Logger.d(TAG, " show exec String: " + outStr);
            return outStr;
        }
    }


    /**
     * 检查系统是否被root
     *
     * @return
     */
    private static synchronized boolean checkGetRootAuth() {
        Logger.d(TAG, "checkGetRootAuth start: " + System.currentTimeMillis());
        Process process = null;
        DataOutputStream os = null;
        try {
            Log.i(TAG, "to exec su");
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("exit\n");
            os.flush();
            int exitValue = process.waitFor();
            Log.i(TAG, "exitValue=" + exitValue);
            if (exitValue == 0) {
                Logger.d(TAG, " fail, checkGetRootAuth exitValue: " + exitValue);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * 判断设备 是否使用代理上网
     * */
    private static boolean isWifiProxy(Context context) {
        final boolean IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
        String proxyAddress;
        int proxyPort;
        if (IS_ICS_OR_LATER) {
            proxyAddress = System.getProperty("http.proxyHost");
            String portStr = System.getProperty("http.proxyPort");
            proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
        } else {
            proxyAddress = android.net.Proxy.getHost(context);
            proxyPort = android.net.Proxy.getPort(context);
        }
        boolean back = (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1);
        if (back) {
            Logger.d(TAG, " fail, isWifiProxy  proxyAddress: " + proxyAddress + proxyPort);
        }
        return back;
    }

}
